/**
 * Created by apple on 16/7/4.
 */
angular.module('starter.spmsLookupService',['ionic'])
  .service('$lookup', function ($timeout,$log,ENV,$q, $dfHttp,$dfDB,$dfCache,$dfUtil) {
    var collection ;

    var choiceItem ;

    $timeout(function () {
      syncLookupData();
    },700);

    //同步值列表
    function saveLookup(obj) {
      var saveFn = function(){
        if (angular.isArray(obj)) {
          for(var i = 0 ; i < obj.length ; i++) {
            lookup = obj[i];
            var dbLookupArray =  collection.find({'lookupCode':lookup.lookupCode,'lookupType':lookup.lookupTpye});
            if (dbLookupArray.length > 0 && lookup.enabledFlag == 'TRUE'){
              //修改
              angular.forEach(dbLookupArray,function(dbLookup){
                angular.forEach(lookup,function(key,value){
                  dbLookup[key] = value ;
                  collection.update(dbLookup);
                });
              });
            }else if (dbLookupArray.length > 0 && lookup.enabledFlag == 'FALSE') {
              angular.forEach(dbLookupArray,function(dbLookup){
                collection.remove(dbLookup);
              });
            }else if(dbLookupArray.length == 0 && lookup.enabledFlag == 'TRUE'){
                collection.insert(lookup);
            }
          }
        } else {
          lookup = obj;
          var dbLookupArray =  collection.find({'lookupCode':lookup.lookupCode,'lookupType':lookup.lookupTpye});
          if (dbLookupArray.length > 0 && lookup.enabledFlag == 'TRUE'){
            //修改
            angular.forEach(dbLookupArray,function(dbLookup){
              angular.forEach(lookup,function(key,value){
                dbLookup[key] = value ;
                collection.update(dbLookup);
              });
            });
          }else if (dbLookupArray.length > 0 && lookup.enabledFlag == 'FALSE') {
            angular.forEach(dbLookupArray,function(dbLookup){
              collection.remove(dbLookup);
            });
          }else if(dbLookupArray.length == 0 && lookup.enabledFlag == 'TRUE'){
            angular.forEach(dbLookupArray,function(dbLookup){
              collection.insert(dbLookup);
            });
          }
        }
      };

      executeDBFunction(saveFn);
    }

    function getWithType(lookupType) {

      var getFn = function() {
        var array = collection.find({'lookupType':lookupType});
        //console.log(lookupType+':'+array);
        return array ;
      }
      return executeDBFunction(getFn);
    }

    function get() {
      var collection = $dfDB.collectionLookupDBSync("syncLookupCollection");
      var array = collection.find({});
      return array;
    }

    function getWithCode(lookupCode,options) {
      if(!angular.isString(lookupCode)){
        return executeDBFunction(function(){
          return {};
        });
      }
      var getFn = function() {
        var array = collection.find({'lookupCode':lookupCode});
        if(array.length > 0){
          var lookup = array[0];
          var copyLookup = {};
          angular.copy(lookup,copyLookup);
          copyLookup.options = options ;
          return copyLookup;
        }else {
          return {};
        }
      }

      return executeDBFunction(getFn);
    }


    function collectionDB(fn){
      if(typeof(collection) == 'undefined'){
        $dfDB.collectionLookupDB("syncLookupCollection").collectionSuccess(function(col) {
          collection = col;
          if(typeof(fn) == 'function'){
            return fn();
          }
        });
      }else {
        return fn();
      }
    }

    //创建collection并执行操作方法
    function executeDBFunction(fn) {
      var deferred = $q.defer();
      var promise = deferred.promise;

      if(typeof(collection) == 'undefined'){
        $dfDB.collectionLookupDB("syncLookupCollection").collectionSuccess(function(col) {
          collection = col;
          if(typeof(fn) == 'function'){
            deferred.resolve(fn());
          }
        });
      }else {
        deferred.resolve(fn());
      }

      promise.executeSuccess = function(fn){
        promise.then(fn);
        return promise ;
      };

      return promise ;
    }

    function syncLookupData(){
      var array = get();

      var time = $dfCache.getObject('lookupLastupDate');
      if(!angular.isString(time)) {
        time = '1970-01-01 01:01:01';
      }

      if(!array || !angular.isArray(array) || array.length == 0){
        time = '1970-01-01 01:01:01';
      }

      $dfHttp.get("api/others/syncLookupValues.json",{"lastUpdateDate":time})
        .success(function(data){
          if(data.code == 'SUCCESS') {
            var lookupArray = [];

            for(var i = 0 ; i < data.data.length ;i++){
              var lookup = data.data[i];
              for(var j = 0 ; j < lookup.spmsLookupValueList.length ; j++) {
                var meaning = lookup.spmsLookupValueList[j];
                meaning.lookupType = lookup.lookupType ;
                meaning.lookupName = lookup.lookupName ;
                meaning.description = lookup.description ;

                lookupArray.push(meaning);
              }
            }

            //TODO:
            saveLookup(lookupArray);
            var date = new Date();
            var timeString = $dfUtil.convertDateToString(date);
            $dfCache.putObject('lookupLastupDate',timeString);

            //存储数据
            $dfDB.dbSave();
          }
        })
        .error(function(data){

        });
    }

    return {
      //同步值列表
      syncLookup:syncLookupData,

      //返回type的列表表,数组
      getWithlookupType:function(lookupType){
        return getWithType(lookupType);
      },
      getWithLookupCode:function(lookupCode,options){
        return getWithCode(lookupCode,options);
      },
      sureChoiceItem: function (item) {
         choiceItem = item ;
      },
      getChoiceItem: function() {
        return choiceItem ;
      },
      clearChoiceItem:function() {
        choiceItem = {};
      },
      get:get
    }
  })
